<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
import {useUserStore} from "@/stores/user.js";
import request from "@/utils/request";

const router = useRouter()
const userStore = useUserStore()
const formState = ref({
  username: '',
  password: '',
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
}

const loading = ref(false)


const onFinish = async(values) => {
  loading.value = true
  // 这里应该是实际的登录API调用，现在用模拟实现
  const res = await request.post('/user/login', {
    username: values.username,
    password: values.password,
  })
  if(res.data.code === 200){
    // 先保存用户信息和token
    const user = res.data.user
    userStore.setUser(user)
    const token = res.data.token
    localStorage.setItem('token', token)
    
    // 然后触发登录状态变化事件
    window.dispatchEvent(new Event('login-state-changed'))
    
    loading.value = false
    message.success('登录成功')
    
    // 最后跳转到首页
    router.push('/')
  }
  else{
    loading.value = false
    message.error('登录失败',res.message)
  }
}
</script>

<template>
  <div class="login-container">
    <h2>用户登录</h2>
    <a-form
      :model="formState"
      name="login"
      :rules="rules"
      @finish="onFinish"
      autocomplete="off"
    >
      <a-form-item name="username">
        <a-input v-model:value="formState.username" placeholder="用户名">
          <template #prefix>
            <UserOutlined />
          </template>
        </a-input>
      </a-form-item>

      <a-form-item name="password">
        <a-input-password v-model:value="formState.password" placeholder="密码">
          <template #prefix>
            <LockOutlined />
          </template>
        </a-input-password>
      </a-form-item>

      <a-form-item>
        <a-button 
          type="primary" 
          html-type="submit" 
          :loading="loading" 
          block
        >
          登录
        </a-button>
      </a-form-item>
      
      <a-form-item>
        <div class="form-footer">
          还没有账号？
          <router-link to="/register">立即注册</router-link>
        </div>
      </a-form-item>
    </a-form>
  </div>
</template>

<style scoped>
.login-container {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
}
h2 {
  text-align: center;
  margin-bottom: 30px;
}
.form-footer {
  text-align: center;
}
</style>